<template>
	<div class="line-login-button" @click="goLineLoginPage">
		<slot></slot>
	</div>
</template>

<script>
	import axios from 'axios'
	import queryString from 'querystring'
	export default {
		data() {
			return {}
		},
		props: {
			params: {
				type: Object,
				default () {
					return {}
				}
			}
		},
		created() {},
		mounted() { 
		},
		methods: {
			// 删除Line在地址栏给的参数
			delUrlParam(param) {
				let obj = new window.URL(window.location.href);
				obj.searchParams.delete(param);
				return obj.href;
			},
			getToken(code) {
				const instance = axios.create({
					baseURL: 'https://api.line.me'
				});
				instance({
					url: '/oauth2/v2.1/token',
					method: 'post',
					headers: {
						"Content-Type": "application/x-www-form-urlencoded"
					},
					data: queryString.stringify({
						grant_type: 'authorization_code',
						code,
						redirect_uri: this.params.callbackUri,
						client_id: this.params.lineClientId,
						client_secret: this.params.lineClientSecret,
					})
				}).then(res => {
					history.pushState({}, 0, this.delUrlParam('code'));
					history.pushState({}, 0, this.delUrlParam('state'));
					history.pushState({}, 0, this.delUrlParam('login'));
					console.log(res.data.access_token)
					return instance({
						url: "/oauth2/v2.1/verify",
						method: "post",
						params: {
							id_token: res.data.id_token,
							client_id: this.params.lineClientId
						}
					})
				}).then(res => {
					this.$emit('success', {
						email: res.data.email,
						lineOpenId: res.data.sub,
						nickname: res.data.name,
					})
				}).catch(err => { 
					history.pushState({}, 0, this.delUrlParam('code'));
					history.pushState({}, 0, this.delUrlParam('state'));
					history.pushState({}, 0, this.delUrlParam('login'));
					this.showToast(err.response.data.error)
					this.$emit('error', err.response.data)
				})
			},
			async goLineLoginPage(code) {
				if (!this.params.lineClientId) {
					return console.error(new Error('Please pass on lineClientId'))
				}
				if (!this.params.callbackUri) {
					return console.error(new Error('Please pass on callbackUri'))
				}
				if (!this.params.lineState) {
					return console.error(new Error('Please pass on lineState'))
				}
				if (!this.params.lineClientSecret) {
					return console.error(new Error('Please pass on lineClientSecret'))
				}
				if (!this.params.scope) {
					return console.error(new Error('Please pass on scope'))
				}
				window.location.replace(
					`https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=${this.params.lineClientId}&redirect_uri=${this.params.callbackUri}&state=${this.params.lineState}&scope=${this.params.scope}&nonce=09876xyz`
				)
			},
		},


		components: {}
	}
</script>

<style lang='scss' scoped>
</style>
